package com.mezz.bones.framework.core.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;

/**
 * 接口模型中互相BigDecimal时返回前端精度丢失
 * 可再字段上使用注解
 * @JsonSerialize(using = NumberSerializer.class)
 */
public class FormattedDecimalSerializer extends JsonSerializer<Number> {  // 泛型改为 Number
    @Override
    public void serialize(Number value, JsonGenerator gen, SerializerProvider provider)
            throws IOException {
        // 将任意 Number 类型转换为 BigDecimal，并四舍五入到两位小数
        BigDecimal decimalValue = new BigDecimal(value.toString())
                .setScale(2, RoundingMode.DOWN);
        // 格式化为两位小数字符串
        DecimalFormat df = new DecimalFormat("#0.00");
        String formatted = df.format(decimalValue);
        gen.writeString(formatted);
    }
}